package com.yuanzhi.train;

import java.util.Arrays;

/**
 * @Author: yuanZhi...
 * @Date: created in  2021/12/14 19:33
 */
public class QickSort {
    public static void main(String[] args) {
        int[] arr = {10, 5, 16, 9, 26, 11, 7, 6, 15, -1};
        qickSort(arr, 0, arr.length-1);
        System.out.println(Arrays.toString(arr));
    }

    private static void qickSort(int[] arr, int low, int high) {
        if (low < high) {
            // 获取基准下标
            int pivot = partion(arr, low, high);
            // 左右子表递归
            qickSort(arr, low, pivot - 1);
            qickSort(arr, pivot + 1, high);
        }
    }
    private static void quickSort(int[] arr,int low,int high){
        int i,j,temp,t;
        if(low>high){
            return;
        }
        i=low;
        j=high;
        //temp就是基准位
        temp = arr[low];

        while (i<j) {
            //先看右边，依次往左递减
            while (temp<=arr[j]&&i<j) {
                j--;
            }
            //再看左边，依次往右递增
            while (temp>=arr[i]&&i<j) {
                i++;
            }
            //如果满足条件则交换
            if (i<j) {
                t = arr[j];
                arr[j] = arr[i];
                arr[i] = t;
            }

        }
        //最后将基准为与i和j相等位置的数字交换
        arr[low] = arr[i];
        arr[i] = temp;
        //递归调用左半数组
        quickSort(arr, low, j-1);
        //递归调用右半数组
        quickSort(arr, j+1, high);
    }

    private static int partion(int[] arr, int low, int high) {
        int temp;
        int l = low;
        int pivot = arr[l];
        // 当左右指针没有相遇，就要一直循环下去
        while (low < high){
            // 只要右指针值比基准值大，右指针就一直左移
            while (low < high && arr[high] > pivot){
                high--;
            }
            // 只要左指针值比基准值小，左指针就一直右移
            while (low < high && arr[low] < pivot){
                low++;
            }
            temp = arr[high];
            arr[high] = arr[low];
            arr[low] = temp;
        }
        // 左右指针相遇时，基准值设为此时相遇的值
        temp = pivot;
        arr[low] = temp;
        return low;
    }
}
